﻿using EnvDTE;
using EnvDTE80;
using EnvDTE90;
using FurionPearAdmin.VSIXProject.Templates;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.UI.Design;
using System.Xml.Linq;
using Task = System.Threading.Tasks.Task;

namespace FurionPearAdmin.VSIXProject
{
    /// <summary>
    /// Command handler
    /// </summary>
    internal sealed class Command1
    {
        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 0x0100;

        private static DTE2 _dte;
        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("5bb4dff3-b62a-4603-9aae-c6b0c1c7107c");

        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly AsyncPackage package;

        /// <summary>
        /// Initializes a new instance of the <see cref="Command1"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private Command1(AsyncPackage package, OleMenuCommandService commandService)
        {
            this.package = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var menuCommandID = new CommandID(CommandSet, CommandId);
            var menuItem = new MenuCommand(this.Execute, menuCommandID);
            commandService.AddCommand(menuItem);
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static Command1 Instance
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private Microsoft.VisualStudio.Shell.IAsyncServiceProvider ServiceProvider
        {
            get
            {
                return this.package;
            }
        }

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        public static async Task InitializeAsync(AsyncPackage package)
        {
            // Switch to the main thread - the call to AddCommand in Command1's constructor requires
            // the UI thread.
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);

            OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
            Instance = new Command1(package, commandService);
        }
        public static async Task InitializeAsync(AsyncPackage package, DTE2 dte)
        {
            // Switch to the main thread - the call to AddCommand in Command1's constructor requires
            // the UI thread.
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(package.DisposalToken);

            OleMenuCommandService commandService = await package.GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;
            Instance = new Command1(package, commandService);

            _dte = dte;
        }
        public string ClassZhName = "";
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void Execute(object sender, EventArgs e)
        {
            string ProjectPrefix = "";//项目前缀
            string SelectClassNamespace = "";//命名空间名称
            string ClassSuffix = "weiyi";//选择的类前缀//当前项目类名
            string ClassName = "";
            string QueryField = "";//搜索字段
            Project ProjectsApp = null;
            Project ProjectsWeb = null;
            var Projects = GetSolutionProjects(_dte.Solution);
            foreach (var item in Projects)
            {
                var Names = item.Name.Split('.');
                if (Names.Length < 2) continue;
                if (string.IsNullOrEmpty(ProjectPrefix))
                {
                    ProjectPrefix = Names[0];
                }
                if (item.Name == ProjectPrefix + ".Application")
                {
                    ProjectsApp = item;
                }
                if (item.Name == ProjectPrefix + ".Web.Entry")
                {
                    ProjectsWeb = item;
                }
            }
            // 选择.cs 实体类
            var selectedItems = _dte.ToolWindows.SolutionExplorer.SelectedItems as UIHierarchyItem[];
            var selectedItem = selectedItems[0]?.Object as ProjectItem;
            if (selectedItem == null)
            {
                return;
            }
            // 获取文件的完整路径
            string filePath = selectedItem.FileNames[0];
            var Aattributes = GetAattributeALL(filePath, out SelectClassNamespace);
            var temps = SelectClassNamespace.Split('.');
            if (temps.Length > 0)
            {
                ClassSuffix = temps[temps.Length - 1];
            }

            // 获取类型
            FileCodeModel fileCodeModel = selectedItem.FileCodeModel;
            CodeClass codeClass = GetClass(fileCodeModel.CodeElements);
            ClassName = codeClass.Name;


            #region 后台代码生成
            /// 1.1增加 ClassSuffix 目录 
            var AppRoot = ProjectsApp.ProjectItems.Item(ClassSuffix);
            if (AppRoot == null)
            {
                AppRoot = ProjectsApp.ProjectItems.AddFolder(ClassSuffix);
            }
            //1.2增加 ClassSuffix-下的Dto 目录 
            var AppRootDto = AppRoot.ProjectItems.Item("Dtos");
            if (AppRootDto == null)
            {
                AppRootDto = AppRoot.ProjectItems.AddFolder("Dtos");
            }
            {
                List<string> param = new List<string>();
                param.Add(ClassName);
                param.Add(ProjectsApp.Name + "." + ClassSuffix + ".Dtos");
                param.Add(SelectClassNamespace);
                StringBuilder tempStr = new StringBuilder();
                foreach (var temp in Aattributes)
                {
                    tempStr.Append(AutoTemplate.Format(AutoTemplate.GetSetTemplate, temp.Name, temp.TypeStr, temp.Summary));

                }
                param.Add(tempStr.ToString());
                string content = AutoTemplate.GetContent("Dto.txt", param.ToArray());
                string fileName = $"{ClassName}Dto.cs";
                AddFileToProjectItem(AppRootDto, content, fileName);
            }
            //1.2增加 ClassSuffix-下的Services 目录 
            var AppRootService = AppRoot.ProjectItems.Item("Services");
            if (AppRootService == null)
            {
                AppRootService = AppRoot.ProjectItems.AddFolder("Services");
            }
            {  //IService
                List<string> param = new List<string>();
                param.Add(ClassName);
                param.Add(ProjectsApp.Name + "." + ClassSuffix + "");
                param.Add(SelectClassNamespace);
                string content = AutoTemplate.GetContent("IService.txt", param.ToArray());
                string fileName = $"I{ClassName}Service.cs";
                AddFileToProjectItem(AppRootService, content, fileName);
                //Service
                content = AutoTemplate.GetContent("Service.txt", param.ToArray());
                fileName = $"{ClassName}Service.cs";
                AddFileToProjectItem(AppRootService, content, fileName);
                //AppService
                StringBuilder tempStr = new StringBuilder();
                foreach (var temp in Aattributes)
                {
                    tempStr.Append(AutoTemplate.Format(AutoTemplate.UpdateTemplate, temp.Name));
                }
                param.Add(tempStr.ToString());
                var QueryFile = Aattributes.FirstOrDefault(u => u.TypeStr == "string");
                if (QueryFile != null)
                {
                    QueryField = QueryFile.Name;
                   
                }
                else
                {
                    QueryField = Aattributes[0].Name;

                    //param.Add(Aattributes[0].Name);//查询字段
                }
                param.Add(QueryField);//查询字段
                param.Add(ClassZhName);//6
                content = AutoTemplate.GetContent("AppService.txt", param.ToArray());
                fileName = $"{ClassName}AppService.cs";
                AddFileToProjectItem(AppRoot, content, fileName);
            }

            //

            //2.生成文件

            #endregion

            #region 前端代码生成
            /// 1.1增加 ClassSuffix 目录 
            /// /// 1.1增加目录 Areas /--/Controllers 
            var ProjectsWebAreas = ProjectsWeb.ProjectItems.Item("Areas");
            if (ProjectsWebAreas == null)
            {
                ProjectsWebAreas = AppRoot.ProjectItems.AddFolder("Areas");
            }
            var ProjectsWebAreasSuffix = ProjectsWebAreas.ProjectItems.Item(ClassSuffix);
            if (ProjectsWebAreasSuffix == null)
            {
                ProjectsWebAreasSuffix = ProjectsWebAreas.ProjectItems.AddFolder(ClassSuffix);
            }
            var ProjectsWebAreasSuffixCon = ProjectsWebAreasSuffix.ProjectItems.Item("Controllers");
            if (ProjectsWebAreasSuffixCon == null)
            {
                ProjectsWebAreasSuffixCon = ProjectsWebAreasSuffix.ProjectItems.AddFolder("Controllers");
            }
            //添加控制器
            {
                List<string> param = new List<string>();
        
                param.Add(ProjectPrefix+ $".Web.Entry.Areas.{ClassSuffix}.Controllers");//命名空间
                param.Add(ClassSuffix);
                param.Add(ClassName);
                string content = AutoTemplate.GetContent("FrontController.txt", param.ToArray());
                string fileName = $"{ClassName}Controller.cs";
                AddFileToProjectItem(ProjectsWebAreasSuffixCon, content, fileName);
            }
            //2.视图
            var ProjectsWebAreasSuffixView = ProjectsWebAreasSuffix.ProjectItems.Item("Views");
            if (ProjectsWebAreasSuffixView == null)
            {
                ProjectsWebAreasSuffixView = ProjectsWebAreasSuffix.ProjectItems.AddFolder("Views");
            }
            var ProjectsWebAreasSuffixViewNext = ProjectsWebAreasSuffixView.ProjectItems.Item(ClassName);
            if (ProjectsWebAreasSuffixViewNext == null)
            {
                ProjectsWebAreasSuffixViewNext = ProjectsWebAreasSuffixView.ProjectItems.AddFolder(ClassName);
            }
            {  //Index.cshtml
                List<string> param = new List<string>();
                param.Add(ClassSuffix);//-类文件
                param.Add(ClassName);//类名
                param.Add(QueryField);//搜索字段
                //所有字段显示
                StringBuilder indexTableStr = new StringBuilder();
                StringBuilder indexTableJq = new StringBuilder();
                foreach (var item in Aattributes)
                {
                    string Temp2 = "";
                    if (item.TypeStr == "string" && item.Name.EndsWith("ImgUrl"))
                    {
                        Temp2 = $", templet: '#{item.Name}_@randomId'";
                        indexTableJq.Append($@"
    <script type=""text/html"" id=""{item.Name}_@randomId"">
        <img src=""{{{{ FileHttpApiUrl+ ''+d.{item.Name}}}}}"" style=""width:38px;height:38px"" />
    </script>");
                    }
                    if (item.TypeStr == "bool" )
                    {
                        Temp2 = $", templet: '#{item.Name}_@randomId'";
                        indexTableJq.Append($@"
    <script type=""text/html"" id=""{item.Name}_@randomId"">
        <input type=""checkbox"" name=""{item.Name}""  lay-skin=""switch""  disabled  {{{{ d.{item.Name} == 1 ? ""checked"" : """" }}}}>
    </script>");
                    }
                    if (item.TypeStr.EndsWith("Enum"))//下拉选择
                    {
                        Temp2 = $", templet: '#{item.Name}_@randomId'";
                        string Temp3 = "'TempV'";
                        foreach(var ii in item.SelectItem)
                        {
                            string tempv = $@"d.{item.Name} == {ii.SelectVal}? '{ii.Summary}':'TempV' ";
                            Temp3 = Temp3.Replace("'TempV'", tempv);
                        }
                        Temp3 = Temp3.Replace("'TempV'", "''");

                        indexTableJq.Append($@"
    <script type=""text/html"" id=""{item.Name}_@randomId"">
        <span>{{{{ {Temp3} }}}}</span>
    </script>");

                    }
                    indexTableStr.Append(
                    AutoTemplate.Format(AutoTemplate.IndexTableTemplate, new string[] { item.Name, item.Summary , Temp2 }));
                        //string.Format(AutoTemplate.IndexTableTemplate, item.Name, item.Summary));
                }
                param.Add(indexTableStr.ToString());//Table字段
                param.Add(indexTableJq.ToString());//Jq
                param.Add(ProjectPrefix);//5 @using-- FurionPearAdmin -- .Web.Core;
                string content = AutoTemplate.GetContent("FrontIndex.txt", param.ToArray());
                string fileName = $"index.cshtml";
                AddFileToProjectItem(ProjectsWebAreasSuffixViewNext, content, fileName);
            }
            {  //AddOrEdit.cshtml
                List<string> param = new List<string>();
                param.Add(ClassName);//-类名
                //所有字段显示
                StringBuilder EditInput = new StringBuilder();
                StringBuilder EditInput2 = new StringBuilder();
                StringBuilder EditInput3 = new StringBuilder();
                StringBuilder EditInput4 = new StringBuilder();//定义值
                StringBuilder EditInput5 = new StringBuilder();//提交数据前处理
                StringBuilder EditInput6 = new StringBuilder();//Query查询后处理
                StringBuilder EditInput7 = new StringBuilder();//最后的js
                StringBuilder EditInput8 = new StringBuilder();//新增特色处理

                foreach (var item in Aattributes)
                {
                    if (item.TypeStr == "string" && item.Name.EndsWith("ImgUrl"))
                    {
                      
                        if (!EditInput2.ToString().Contains("upload"))
                        {
                            EditInput2.Append(", 'upload'");
                            EditInput3.AppendLine("        var upload = layui.upload;");
                        }
                        if (!EditInput2.ToString().Contains("element"))
                        {
                            EditInput2.Append(", 'element'");
                            EditInput3.AppendLine("        var element = layui.element;");
                        }
                       
                        EditInput8.Append(AutoTemplate.Format(AutoTemplate.FromImgUrlJQTemplate, new string[] { item.Name }));
                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary,
                            AutoTemplate.Format(AutoTemplate.FromImgUrlTemplate, new string[] { item.Name })));
                        EditInput6.Append(AutoTemplate.Format(AutoTemplate.FromImgUrlQTemplate, new string[] { item.Name }));

                        continue;
                    }
                    if (item.TypeStr == "string" && item.Name.EndsWith("FileUrl"))
                    {
                        if (!EditInput2.ToString().Contains("upload"))
                        {
                            EditInput2.Append(", 'upload'");
                            EditInput3.AppendLine("        var upload = layui.upload;");
                        }
                        if (!EditInput2.ToString().Contains("element"))
                        {
                            EditInput2.Append(", 'element'");
                            EditInput3.AppendLine("        var element = layui.element;");
                        }
                        EditInput8.Append(AutoTemplate.Format(AutoTemplate.FromFlieUrlJQTemplate, new string[] { item.Name }));
                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary,
                            AutoTemplate.Format(AutoTemplate.FromFlieUrlTemplate, new string[] { item.Name })));
                        EditInput6.Append(AutoTemplate.Format(AutoTemplate.FromFlieUrlQTemplate, new string[] { item.Name }));
                        continue;
                    }
                    if (item.TypeStr == "string" && item.Name.EndsWith("Html"))
                    {
                        if (!EditInput2.ToString().Contains("tinymce"))
                        {
                            EditInput2.Append(",'tinymce'");
                            EditInput3.AppendLine("        var tinymce = layui.tinymce;");
                        }
                        if (!EditInput8.ToString().Contains("function initTinymce"))
                        {
                            EditInput8.Append(AutoTemplate.FromHtmlUrlJQTemplate);
                        }

                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary,
                            AutoTemplate.Format(AutoTemplate.FromHtmlUrlTemplate, new string[] { item.Name })));
                        EditInput4.AppendLine($"        var {item.Name}TinymceEle=null;");
                        EditInput5.AppendLine($"            data.field['{item.Name}']= {item.Name}TinymceEle.getContent();");

                        EditInput6.Append(AutoTemplate.Format(AutoTemplate.FromHtmlUrlQTemplate, new string[] { item.Name }));
                        EditInput7.Append(AutoTemplate.Format(AutoTemplate.FromHtmlUrlQTemplate.Replace("                        ", "            "), new string[] { item.Name }));
                        
                        continue;
                    }
                    if (item.TypeStr.EndsWith ("Enum"))//下拉选择
                    {
                         
                        string TempS = @" <select name=""{0}"" lay-verify=""required"">{1}</select>";
                        string option = @"
                                    <option value=""{0}"">{1}</option>";
                        string TempSum1 = "";
                        int index = 0;
                        foreach (var ii in item.SelectItem)
                        {
                            if(string.IsNullOrEmpty(ii.SelectVal))
                                TempSum1 += string.Format(option, index, ii.Summary);
                            else
                                TempSum1 += string.Format(option, ii.SelectVal, ii.Summary);

                            index++;
                        }
                        string TempSS = string.Format(TempS, item.Name, TempSum1);
                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary, TempSS));
                        continue;
                    }
                    if (item.TypeStr.StartsWith("DateTime")  )//时间
                    {
                        if (!EditInput2.ToString().Contains("laydate"))
                        {
                            EditInput2.Append(",'laydate'");
                            EditInput3.AppendLine("        var laydate = layui.laydate;");
                        }

                        string TempS = $"<input type=\"text\" class=\"layui-input\" name=\"{item.Name}\" id=\"{item.Name}Ele\">\r\n";
                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary, TempS));
                        string JQ = $@"  
                            //执行一个laydate实例
        laydate.render({{
               elem: '#{item.Name}Ele', //指定元素
               type: 'datetime',
               format: 'yyyy-MM-dd HH:mm:ss'
               //type: 'time', // 选择时间类型
               //format: 'HH:mm:ss'   //控制文本显示的内容格式
         }});";
                        EditInput4.Append(JQ);
                        continue;
                    }
                    if (item.TypeStr == "int")//数字输入
                    {

                        string TempS = $"<input type=\"number\" name=\"{item.Name}\" required  lay-verify=\"required\"  autocomplete=\"off\" class=\"layui-input\">";
                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary, TempS));
                        continue;
                    }
                    if (item.TypeStr == "bool")//开关
                    {

                        string TempS = $"<input type=\"checkbox\" name=\"{item.Name}\" lay-skin=\"switch\" value=\"true\">";
                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary, TempS));
                        continue;
                    }
                    //if (item.TypeStr == "string")//默认 输入框
                    {
                        string TempS = $"<input type=\"text\" name=\"{item.Name}\" required  lay-verify=\"required\"  autocomplete=\"off\" class=\"layui-input\">";
                        EditInput.Append(string.Format(AutoTemplate.FromTemplate, item.Summary, TempS));
                        continue;
                    }
                    

                }
                param.Add(EditInput.ToString());//-字段

                param.Add(EditInput2.ToString());
                param.Add(EditInput3.ToString());
                param.Add(EditInput4.ToString());
                param.Add(EditInput5.ToString());
                param.Add(EditInput6.ToString());
                param.Add(EditInput7.ToString());
                param.Add(EditInput8.ToString());



                string content = AutoTemplate.GetContent("FrontAddOrEdit.txt", param.ToArray());
                string fileName = $"AddOrEdit.cshtml";
                AddFileToProjectItem(ProjectsWebAreasSuffixViewNext, content, fileName);
            }



            //

            //2.生成文件

            #endregion


            //==================End
            SelectedItem selectedItem1 = _dte.SelectedItems.Item(1);
        

            Project project1 = _dte.Solution.Projects.Item(1); // 获取当前解决方案的第一个项目
            ProjectItem projectItem1 = project1.ProjectItems.Item(1); // 获取项目的第一个文件

            //// 获取文件名
            //string fileName = selectedItem1.ProjectItem.get_FileNames(1);
            //if (selectedItems == null || selectedItems.Length == 0)
            //{

            //    return;
            //}
           






  /*
            // 获取文件代码模型
            FileCodeModel fileCodeModel = selectedItem.FileCodeModel;

            // 获取类型
            CodeClass codeClass = GetClass(fileCodeModel.CodeElements);

            // 遍历类的属性
            foreach (CodeElement element in codeClass.Members)
            {

                if (element.Kind == vsCMElement.vsCMElementProperty)
                {
                    CodeProperty property = element as CodeProperty;
                    System.Diagnostics.Debug.WriteLine(property.Name);
                    System.Diagnostics.Debug.WriteLine(property.Type.TypeKind.ToString());
                    //CodeProperty property = element as CodeProperty;

                }
            }
            Properties properties = selectedItem.Properties;
            foreach (Property property in properties)
            {
                Debug.WriteLine($"  Property Name: {property.Name}, Value: {property.Value}");
            }
            return;
            // 项目
            var project = selectedItem.ContainingProject;
            if (project == null)
            {
                return;
            }
            // 项目名
            var projectName = project.Name;
  */
            ThreadHelper.ThrowIfNotOnUIThread();
            string message = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            string title = "通知";
            message = "生成成功";

            // Show a message box to prove we were here
            VsShellUtilities.ShowMessageBox(
                this.package,
                message,
                title,
                OLEMSGICON.OLEMSGICON_INFO,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
        }



        #region 辅助方法
        /// <summary>
        /// 获取所有项目
        /// </summary>
        /// <param name="projectItems"></param>
        /// <returns></returns>
        private IEnumerable<ProjectItem> GetProjects(ProjectItems projectItems)
        {
            foreach (EnvDTE.ProjectItem item in projectItems)
            {
                yield return item;

                if (item.SubProject != null)
                {
                    foreach (EnvDTE.ProjectItem childItem in GetProjects(item.SubProject.ProjectItems))
                        if (childItem.Kind == EnvDTE.Constants.vsProjectItemKindSolutionItems)
                            yield return childItem;
                }
                else
                {
                    foreach (EnvDTE.ProjectItem childItem in GetProjects(item.ProjectItems))
                        if (childItem.Kind == EnvDTE.Constants.vsProjectItemKindSolutionItems)
                            yield return childItem;
                }
            }
        }

        /// <summary>
        /// 获取解决方案里面所有项目
        /// </summary>
        /// <param name="solution"></param>
        /// <returns></returns>
        private List<ProjectItem> GetSolutionProjectsItme(Solution solution)
        {
            List<ProjectItem> projectItemList = new List<ProjectItem>();
            var projects = solution.Projects.OfType<Project>();
            foreach (var project in projects)
            {
                var projectitems = GetProjects(project.ProjectItems);

                foreach (var projectItem in projectitems)
                {
                    projectItemList.Add(projectItem);
                }
            }

            return projectItemList;
        }
        private List<Project> GetSolutionProjects(Solution solution)
        {
            List<ProjectItem> projectItemList = new List<ProjectItem>();
            var projects = solution.Projects.OfType<Project>();
           

            return projects.ToList();
        }
        /// <summary>
        /// 获取类
        /// </summary>
        /// <param name="codeElements"></param>
        /// <returns></returns>
        private CodeClass GetClass(CodeElements codeElements)
        {
            var elements = codeElements.Cast<CodeElement>().ToList();
            var result = elements.FirstOrDefault(codeElement => codeElement.Kind == vsCMElement.vsCMElementClass) as CodeClass;
            if (result != null)
            {
                return result;
            }
            foreach (var codeElement in elements)
            {
                result = GetClass(codeElement.Children);
                if (result != null)
                {
                    return result;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取当前所选文件去除项目目录后的文件夹结构
        /// </summary>
        /// <param name="selectProjectItem"></param>
        /// <returns></returns>
        private string GetSelectFileDirPath(Project topProject, ProjectItem selectProjectItem)
        {
            string dirPath = "";
            if (selectProjectItem != null)
            {
                //所选文件对应的路径
                string fileNames = selectProjectItem.FileNames[0];
                string selectedFullName = fileNames.Substring(0, fileNames.LastIndexOf('\\'));

                //所选文件所在的项目
                if (topProject != null)
                {
                    //项目目录
                    string projectFullName = topProject.FullName.Substring(0, topProject.FullName.LastIndexOf('\\'));

                    //当前所选文件去除项目目录后的文件夹结构
                    dirPath = selectedFullName.Replace(projectFullName, "");
                }
            }

            return dirPath.Substring(1);
        }

        /// <summary>
        /// 添加文件到项目中
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="content"></param>
        /// <param name="fileName"></param>
        private void AddFileToProjectItem(ProjectItem folder, string content, string fileName)
        {
            try
            {
                string path = Path.GetTempPath();
                Directory.CreateDirectory(path);
                string file = Path.Combine(path, fileName);
                File.WriteAllText(file, content, System.Text.Encoding.UTF8);
                try
                {
                    var existingFile = folder.ProjectItems.Cast<ProjectItem>().FirstOrDefault(item => item.Name == Path.GetFileName(file));
                    if (existingFile != null)
                    {
                        // 如果存在，则删除
                        existingFile.Delete();
                    }
                 
                    
                    
                    folder.ProjectItems.AddFromFileCopy(file);
                }
                finally
                {
                    File.Delete(file);
                }
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 添加文件到指定目录
        /// </summary>
        /// <param name="directoryPathOrFullPath"></param>
        /// <param name="content"></param>
        /// <param name="fileName"></param>
        private void AddFileToDirectory(string directoryPathOrFullPath, string content, string fileName = "")
        {
            try
            {
                string file = string.IsNullOrEmpty(fileName) ? directoryPathOrFullPath : Path.Combine(directoryPathOrFullPath, fileName);
                File.WriteAllText(file, content, System.Text.Encoding.UTF8);
            }
            catch (Exception ex)
            {

            }
        }
        #endregion

      
        /// <summary>
        /// 获取类 属性
        /// </summary>
        /// <param name="file">类的url</param>
        /// <returns></returns>
        private List<Aattribute> GetAattributeALL(string fileUrl,out string namespaceName)
        {
            string Content = File.ReadAllText(fileUrl);
            namespaceName = "";
            string[] Contents = Content.Split('\r');
            bool enumState = false;
            string enumName = "";
            List<Aattribute> enumData = new List<Aattribute>();

            Dictionary<string, List<Aattribute>>  enumDatas= new Dictionary<string, List<Aattribute>>();

            bool summaryState = false;
            string summaryName = "";

            bool ClassState = false;
            string ClassName = "";
            List<Aattribute> Aattributes = new List<Aattribute>();
            int enumDataIndex = 0;
            foreach (string item in Contents)
            {
                if (item.Contains("namespace "))
                {
                    namespaceName= item.Replace("namespace ", "").Replace("\n", "")
                        .Replace("\t", "").Trim();
                }
                    
                if (summaryState)
                {
                    summaryName = item.TrimEnd().Replace("///", "")
                        .Replace("\n", "")
                        .Replace("\t", "").Trim();
                    if (string.IsNullOrEmpty(ClassZhName))
                    {
                        ClassZhName = summaryName;
                    }
                }
                if (item.Contains("/// <summary>") && summaryState==false)
                {
                    summaryState = true;
                    summaryName = "";
                }
                if (!string.IsNullOrEmpty(summaryName))
                {
                    summaryState = false;
                }


                if (enumState)
                {
                    if (!item.Contains("///") && !item.Contains("{") && !item.Contains("}"))
                    {
                        Aattribute data = new Aattribute();
                        data.Name = item.Replace(",", "").Replace("\n", "")
                        .Replace("\t", "");
                        if (data.Name.Contains("="))
                        {
                            var temp1 = data.Name.Split('=');
                            data.Name = temp1[0];
                            int tempInt = 0;
                            int.TryParse(temp1[1], out tempInt);
                            data.SelectVal = tempInt.ToString();
                            enumDataIndex = tempInt;
                        }
                        else
                        {
                            data.SelectVal = enumDataIndex.ToString();

                        }
                        data.Summary = summaryName.Trim();
                        enumData.Add(data);
                        enumDataIndex++;
                    }
                }
                if (item.Contains(" enum "))
                {
                    enumState = true;
                    enumData = new List<Aattribute>();
                    enumDataIndex = 0;
                    var tempData = item.TrimEnd().Split(' ');
                    enumName = tempData[tempData.Length - 1].Trim();
                }
                if (enumState && item.Contains("}"))
                {
                    enumState = false;
                    enumDatas.Add(enumName, enumData);
                }

                string TempRegex = "{ get; set; }";
                if (ClassState)
                {
                    if (item.Contains(TempRegex))
                    {
                        Aattribute data = new Aattribute();
                        var items = item.Replace(TempRegex, "").Trim().Split(' ');
                        data.TypeStr = items[1].Trim();
                        data.Name = items[2].Trim();
                        data.Summary =summaryName.Trim();
                        Aattributes.Add(data);
                    }
                }
                if (item.Contains(" class "))
                {
                    ClassState = true;

                }
                if (ClassState && item.Contains("}") & !item.Contains(TempRegex))
                {
                    ClassState = false;
                   
                }

            }
            foreach (var item in Aattributes)
            {
                if (enumDatas.Any(u => u.Key == item.TypeStr))
                {
                    item.SelectItem = enumDatas[item.TypeStr];
                }

            }
            
            return Aattributes;
        }


     
    }


    public class Aattribute
    {
        public string Name { get; set; }
        public string TypeStr { get; set; }
        public string Summary { get; set; }
        public string SelectVal { get; set; }
        public List<Aattribute> SelectItem { get; set; }
    }
}
